//
//  ViewController.m
//  UDPDemo
//
//  Created by Ivan on 17/1/5.
//  Copyright © 2017年 Ivan. All rights reserved.
//



#import "ViewController.h"

// UPD class
#import "AsyncUdpSocket.h"

// 配置文件
#import "Config.h"


@interface ViewController ()<UITextFieldDelegate>
{
    
    AsyncUdpSocket      *   udpSocketReceive;   // 接受信息的UDP
    BOOL                    isRunning;
    
    AsyncUdpSocket      *   udpSocketSend;

    long                    getTagIndex;
    int                     getTagReceive;
    int                     getPort;
    UITextField         *   textInputIp;
    UITextField         *   textInputContent;
    
    UITextView          *   getTextView;
    
}


@end

@implementation ViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 初始化 数据
    [self initData];
    
    // 创建 接受者信息的UDP
    [self createReceive];
    
    // 创建 发送信息的 UDP
    [self createSendUDPSocket ];
    
    // 创建视图
    [self createUIView];
    
}

#pragma mark - 初始化 数据 --
-(void)initData
{
    getPort = 6000;    // 端口 设定为 : 6000
    getTagIndex = 1;
    getTagReceive = 200; //  接受数据包 的标签
}

#pragma mark - 创建 接受者信息的UDP --
-(void)createReceive
{
    // 创建 接受 信息的UDP --
    udpSocketReceive = [[AsyncUdpSocket alloc] initWithDelegate:self];
}

#pragma mark - 创建 发送信息的 UDP --
-(void)createSendUDPSocket
{
    // 创建 发送信息的 UDP --
    udpSocketSend = [[AsyncUdpSocket alloc] initWithDelegate:self];
    
    //启动本地端口
    [udpSocketSend localPort];
    
    NSError * error = nil;
    if (![udpSocketSend bindToPort:0 error:&error])
    {
        NSLog(@"Error binding: %@", error);
        return;
    }
    
    //发送广播设置
    [udpSocketSend enableBroadcast:YES error:&error];
    
    // 接收数据包 -1表示一直等接收  tag 200 表示当前接收数据包
    [udpSocketSend receiveWithTimeout:-1 tag: getTagReceive ];
    
}

#pragma mark - 创建 视图 --
-(void)createUIView
{
    UIButton * btnStartStop = [UIButton buttonWithType: UIButtonTypeCustom ];
    btnStartStop.frame = CGRectMake( 10, 100, 150, 50 );
    btnStartStop.backgroundColor = [UIColor yellowColor];
    [btnStartStop setTitleColor:[UIColor blueColor] forState: UIControlStateNormal ];
    [btnStartStop setTitle: @"开启服务器" forState: UIControlStateNormal ];
    btnStartStop.titleLabel.font = [UIFont systemFontOfSize: 13 ];
    [btnStartStop addTarget: self action:@selector(startStopPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: btnStartStop ];
    
    // 开启 服务器 --
//    [self startStopPressed: btnStartStop ];
    
    
    UIButton * btnSendMsg = [UIButton buttonWithType: UIButtonTypeCustom ];
    btnSendMsg.frame = CGRectMake( 10, btnStartStop.frame.origin.y + btnStartStop.frame.size.height + 10 , 100, 50 );
    btnSendMsg.backgroundColor = [UIColor grayColor];
    [btnSendMsg setTitle: @"发送" forState: UIControlStateNormal ];
    btnSendMsg.titleLabel.font = [UIFont systemFontOfSize: 13 ];
    [btnSendMsg setTitleColor:[UIColor blueColor] forState: UIControlStateNormal ];
    [btnSendMsg addTarget: self action:@selector(sendMsg:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: btnSendMsg ];
    
    CGFloat textInputX = btnSendMsg.frame.origin.x * 2 + btnSendMsg.frame.size.width;
    CGFloat textInputW = self.view.frame.size.width - btnSendMsg.frame.origin.x - textInputX;
    
    textInputIp = [[UITextField alloc] init];
    textInputIp.frame = CGRectMake( textInputX, btnSendMsg.frame.origin.y, textInputW, btnSendMsg.frame.size.height );
    textInputIp.backgroundColor = [UIColor redColor];
    textInputIp.delegate = self;
    textInputIp.placeholder = @"输入 IP";
    
    textInputIp.text = [self getIPAddress];
    
    [self.view addSubview: textInputIp ];
    
    textInputContent = [[UITextField alloc] init];
    textInputContent.frame = CGRectMake( btnSendMsg.frame.origin.x, btnSendMsg.frame.origin.y + btnSendMsg.frame.size.height + 10, (self.view.frame.size.width - btnSendMsg.frame.origin.x * 2 ), btnSendMsg.frame.size.height );
    textInputContent.backgroundColor = [UIColor redColor];
    textInputContent.delegate = self;
    textInputContent.placeholder = @"输入 发送信息";
    [self.view addSubview: textInputContent ];
    
    
    CGFloat getTextViewY = textInputContent.frame.origin.y + textInputContent.frame.size.height + 10 ;
    CGFloat getTextViewH = self.view.frame.size.height - getTextViewY - 10;
    
    getTextView = [[UITextView alloc] init];
    getTextView.frame = CGRectMake( textInputContent.frame.origin.x, getTextViewY , textInputContent.frame.size.width, getTextViewH );
    getTextView.font = [UIFont systemFontOfSize: 13 ];
    getTextView.backgroundColor = [UIColor grayColor];
    getTextView.textColor = [UIColor redColor];
    [self.view addSubview: getTextView ];
    
    
    
}


#pragma mark - 获取当前IP --
- (NSString *)getIPAddress
{
    
    /*
        这里的ip 值，需要根据自己设备IP 来设定。
     */
    
    NSString * ip = @"192.168.0.137";
    
    //把得到的目标ip 最后的数字更换为255（意思是搜索全部的）  -- 需要注意
    
    /*
     1、当为 模拟器 时， 给真机 发信息
     2、当为 真机 时，给模拟器 发信息
     */
    if ( IsSimulator ) {
        // 模拟器的环境下 给 真机 （手机） IP 发消息
        ip = @"192.168.0.134";
        
    }else{
        // 真机环境下 给 模拟器 (mac) IP 发消息
        ip = @"192.168.0.137";
        
    }
    
    return ip;
    
}


- (void)logError:(NSString *)msg
{
    NSLog( @"--logError--getMsg--%@", msg );
    
}

- (void)logInfo:(NSString *)msg
{
    NSLog( @"--logInfo--getMsg--%@", msg );
    
}

- (void)logMessage:(NSString *)msg
{
    NSLog( @"--logMessage--getMsg--%@", msg );
    
    if ( getTextView.text.length ) {
        getTextView.text = [NSString stringWithFormat:@"%@\n%@", getTextView.text, msg ];
        
    }else{
        getTextView.text = [NSString stringWithFormat:@"%@", msg ];
        
    }
    
}


#pragma mark - 开启 或 关闭 服务器 --
-(void)startStopPressed:(UIButton *)btn
{
    if (isRunning)
    {
        // STOP udp echo server
        
        [udpSocketReceive close];
        
        [self logInfo:@"Stopped Udp Echo server"];
        isRunning = false;
        
        [btn setTitle: @"开启服务器" forState: UIControlStateNormal ];
        
    }else{
        // START udp echo server
        
        if ( getPort < 0 || getPort > 65535 ){
            getPort = 0;
        }
        
        NSError * error = nil;
        
        if (![udpSocketReceive bindToPort: getPort error:&error]){
            NSString * getError = [NSString stringWithFormat:@"Error starting server (bind): %@", error ];
            [self logError: getError ];
            return;
        }
        
        [udpSocketReceive receiveWithTimeout:-1 tag: getTagReceive ];
        
        NSString * getMsg = [NSString stringWithFormat: @"Udp Echo server started on port %hu", [udpSocketReceive localPort] ];
        [self logInfo: getMsg ];
        isRunning = YES;
        
        [btn setTitle: @"关闭服务器" forState: UIControlStateNormal ];

    }
}


#pragma mark -- 接受信息 --
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
    NSString * msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
//    NSString * sData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    NSString * msg = [NSString stringWithFormat:@"%@:%d %@", host, port, sData];
//    NSLog( @"----msg: %@", msg );
    
    if ( tag == 200 ) {
        // 接受信息 成功
        [self logMessage:FORMAT(@"RECV: %@", msg)];
        
    }else{
        
    }
    
    [udpSocketReceive receiveWithTimeout:-1 tag: getTagReceive ];
    
    return YES;
}


#pragma mark - 发送消息 --
- (void)sendMsg:(UIButton *)sender
{
    NSString * host = textInputIp.text;
    if ([host length] == 0)
    {
        [self logError:@"Address required"];
        return;
    }
    
    if ( getPort <= 0 || getPort > 65535)
    {
        [self logError:@"Valid port required"];
        return;
    }
    
    NSString * msg = textInputContent.text;
    if ([msg length] == 0)
    {
        [self logError:@"Message required"];
        return;
    }
    
    NSData * data = [msg dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocketSend sendData: data toHost:host port: getPort withTimeout:-1 tag: getTagIndex ];
    
    
    [self logMessage:FORMAT(@"SENT (%i): %@", (int)getTagIndex, msg)];
    
    getTagIndex++;
}

#pragma mark - 开始发送 --
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog( @"didSendDataWithTag--%ld", tag );
    
}


#pragma mark - 发送失败 --
- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    NSLog( @"didNotSendDataWithTag--%ld", tag );
    
    [self logError: error.description ];
    
}


#pragma mark - 关闭广播 --
-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock
{
    NSLog(@"关闭啦");
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
